package com.aaa.sys.controller;


import com.aaa.util.JwtUtils;
import com.aaa.vo.R;
import com.aaa.sys.entity.Dict;
import com.aaa.sys.service.DictService;
import com.aaa.sys.service.DictTypeService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 基础字典 前端控制器
 * </p>
 *
 * @author ykq
 * @since 2020-12-08
 */
@RestController
@RequestMapping("/system/dict")
public class DictController {

    @Autowired
    private DictService dictService;

    @Autowired
    private DictTypeService dictTypeService;

    @GetMapping("findByDictTypeId/{dictTypeId}")
    public R findByDictTypeId(@PathVariable Long dictTypeId){
        QueryWrapper<Dict> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dict_type_id",dictTypeId);
        List<Dict> list = this.dictService.list(queryWrapper);
        return R.ok().data("dicts",list);
    }

    @PostMapping("saveDict")
    public R saveDict(@RequestBody Dict dict, HttpServletRequest request){
        try {
            dict.setCreateTime(new Date());
            dict.setCreateUser(JwtUtils.getMemberIdByJwtToken(request.getHeader("token")));
            this.dictService.save(dict);
            return R.ok().message("添加数据字典成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("添加数据字典失败");
        }
    }
    @PostMapping("updateDict")
    public R updateDict(@RequestBody Dict dict, HttpServletRequest request){
        try {
            dict.setUpdateTime(new Date());
            dict.setUpdateUser(JwtUtils.getMemberIdByJwtToken(request.getHeader("token")));
            this.dictService.updateById(dict);
            return R.ok().message("修改数据字典成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("修改数据字典失败");
        }
    }

    @DeleteMapping("deleteDict/{dictId}")
    public R deleteDict(@PathVariable Long dictId){
        try {
            this.dictService.removeById(dictId);
            return R.ok().message("删除数据字典成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("删除数据字典失败");
        }
    }

    @GetMapping("findById/{dictId}/{dictTypeId}")
    public R findById(@PathVariable Long dictId,@PathVariable Long dictTypeId){
          return R.ok().data("dict",this.dictService.getById(dictId)).data("dictType",this.dictTypeService.getById(dictTypeId));
    }



}

